package com.totoro.rocketmq.demo;

import com.alibaba.rocketmq.client.exception.MQBrokerException;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.remoting.common.RemotingHelper;
import com.alibaba.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;

/**
 * Created by Niki on 2018/6/7 8:42
 */
@Component
public class RocketMQProducer {

    @Value("${apache.rocketmq.producer.producerGroup}")
    private String producerGroup;

    @Value("${apache.rocketmq.namesrvAddr}")
    private String namesrvAddr;

    private static String topic = "RC_ORDER_PLAT_APR_SUCC";

    @PostConstruct
    public void defaultMQProducer() {
        //消息客户端
        DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
        //设置NameServer地址，逗号分隔
        producer.setNamesrvAddr(namesrvAddr);

        try {
            /*
            * producer在调用前使用start()方法初始化，初始化一次即可
            * 不可每次发送消息都调用start初始化
            * */
            producer.start();

            Message message = new Message(topic, null, "Hello RocketMQ".getBytes(RemotingHelper.DEFAULT_CHARSET));

            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            for (int i = 0; i < 1000; i++) {
                SendResult result = producer.send(message);
                System.out.println(result.getMsgId()+"的发送状态为："+ result.getSendStatus());
            }
            stopWatch.stop();
            System.out.println("发送一千条消息耗时：" + stopWatch.getTotalTimeMillis()+"毫秒");
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        }finally{
            producer.shutdown();
        }

    }

}
